package com.iam.api.controller;


import cn.dev33.satoken.dao.SaTokenDao;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iam.api.service.SysRoleService;
import com.iam.api.service.SysUserRoleService;
import com.iam.api.service.SysUserService;
import com.iam.core.base.BaseCommonController;
import com.iam.core.base.BaseCommonService;
import com.iam.core.config.IamApplicationconfig;
import com.iam.core.config.Rsaconfig;
import com.iam.core.entities.Result;
import com.iam.core.model.SysRole;
import com.iam.core.model.SysUser;
import com.iam.core.model.SysUserRole;
import com.iam.core.utils.ResultUtil;
import com.iam.core.utils.RsaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.rsa.crypto.RsaAlgorithm;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <用户控制器>
 *
 * @author baily
 * @date 2019/7/5
 * @since 1.0
 **/
@RestController
@RequestMapping("/api/sysUser")
public class SysUserController extends BaseCommonController<SysUser> {

    @Autowired
    private SysUserService<SysUser> service;

    @Autowired
    private SysRoleService<SysRole> roleService;

    @Autowired
    private SysUserRoleService<SysUserRole> userRoleService;

    public static RsaUtil rsaUtil;

    @Autowired
    private IamApplicationconfig iamApplicationconfig;

    @Autowired
    private SaTokenDao saTokenDao;

    static {
        rsaUtil = new RsaUtil();
        Rsaconfig rsaconfig = new Rsaconfig();
        rsaconfig.setAlgorithm(RsaAlgorithm.DEFAULT);
        rsaconfig.setPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvrvh/BoZ6bcnCltEWSyT9WnDOlfwXOHWotOS3j1rgE50UjQ82CFKArvVj5qpTT2AJAlDYz0EzTDNXKluyPcOzxL7qJSdASjJuR5ewrXJcL/6Q51465vQqijlkYrZx/kg57Oy5eVSJKZhTpNiwAM0iJ7Mjt7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mlQCYk9tCsguW5FW46IsQjrqo5COnpP3ffSD9lDN48FmEHowY/QGwVCa0fd6HcCgYEAzWe/Lr4C1gC16HyWoDMMgz4h3369kRflrxE0xC12n+6l+PypxfZQey31NFj3xG0ZsS+SEiI89xH8L64cwJHWlahBNLb5DoBFVcgm2jiqEB00O1rBAd89DDQ4rK7sXVf0Sau+/chAUDKH6ZAzR8kQRfQn0iQ3jrga0cik/CKrL8sCgYBbM7M5wAZjV69fo/IM/UEmLCdMxEzfd1+rOlW76yZpb7be41vupvCGzfmW4jzNkTc16FAuHyv8JOM8DrriPHagdPIKCyzQLbxLuD1rz1YyB2B0OoNypSz/SuyrOBt0HSNkiL+iGCJgvTyXNNVrLzgSwNSsrdzXJo35T/NDpbcF0QKBgHT5YizyVJcerHmLihQNPlD3bz7h5H7ehxTdzZjy8x09QRO8f8qW7VpY381B5UfdgcYf+yWMjf9+JInas9EOvI9Z1Fh64vbZIaMqasXXgzHOD9LFaijwwslSa/wbWcwGrL3PquLHyahiPnhKgIme/T95Pbw0l9cVDWDuzNYxwB9lAoGAYF4TSeEjbnQKoo5/H3bsTOdr0c27KIyBKrpNfXosy01l2f5kLdFmDDGvIgvVXtN3Tt3Jsi+NWb6zaPgEWGpbGqVvtPnDZVpnTB8kV/fTw5puUbg6JgRn2jUix2yyRj5hcceuv6kvmz0SNElmWxucbIUD3fcoItrWBjD2BM5z3qI=");
        rsaUtil.setRsAconfig(rsaconfig);
    }

    @Override
    public boolean exist(SysUser entity) {
        return service.count(new QueryWrapper<SysUser>().eq("login_name", entity.getLoginName())) > 0;
    }

    @Override
    public Result save(@RequestBody SysUser entity) {
        SysRole role = roleService.getOne(new QueryWrapper<SysRole>().eq("role_name", entity.getRoleName()), false);
        if (!ObjectUtils.isEmpty(role)) {
            entity.setRoleId(role.getRoleId());
        }
        Result save = super.save(entity);
        entity.setWorkNum(new DecimalFormat("P000000").format(entity.getUserId()));
        service.updateById(entity);
        return save;
    }

    @GetMapping("/managers")
    public Result managers() {
        SysRole manager = roleService.getOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleName, "Manager"), false);
        if (ObjectUtils.isEmpty(manager)) {
            return ResultUtil.notFound("未找到相关配置");
        }
        List<SysUserRole> list = userRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getRoleId, manager.getRoleId()));
        List<Integer> collect = list.stream().map(SysUserRole::getUserId).collect(Collectors.toList());
        List<SysUser> users = service.list(new LambdaQueryWrapper<SysUser>().in(SysUser::getUserId, collect));
        return ResultUtil.success(users);
    }

    @PostMapping("/updates")
    private Result updates(@RequestBody SysUser user) {
        for (String userId : user.getUserIds().split(IamApplicationconfig.SYMBLE_COMMA)) {
            SysUser sysUser = new SysUser();
            sysUser.setUserId(Integer.parseInt(userId));
            sysUser.setCompanyId(user.getCompanyId());
            sysUser.setCompany(user.getCompany());
            service.updateById(sysUser);
        }
        return ResultUtil.success();
    }

    @PutMapping
    public Result update(@RequestBody SysUser entity) {
        SysRole role = roleService.getOne(new QueryWrapper<SysRole>().eq("role_name", entity.getRoleName()), false);
        if (!ObjectUtils.isEmpty(role)) {
            entity.setRoleId(role.getRoleId());
        }
        if(!ObjectUtils.isEmpty(entity.getPassword())) {
            entity.setPassword(rsaUtil.encryptString(entity.getPassword()));
        }
        return super.update(entity);
    }

    @PostMapping("/resetPasswd")
    public Result restPw(@RequestBody SysUser user) throws Exception {
        // 使用公钥加密
        user.setPassword(rsaUtil.encryptString(iamApplicationconfig.getDefaultPassword()));
        // 使用私钥解密
        return ResultUtil.success(service.updateById(user));
    }

    @GetMapping("/list")
    public Result list(@RequestParam("ids") String ids) {
        String[] split = ids.split(",");
        List<String> list = Arrays.asList(split);
        List<SysUser> users = getiService().list(new QueryWrapper<SysUser>().in("id", list));
        return ResultUtil.success(users);
    }

    @Override
    public BaseCommonService<SysUser> getiService() {
        return service;
    }

    @Override
    public String getMouduleName() {
        return "用户";
    }
}

